import jwt from 'jsonwebtoken'
import { CONFIG } from '@src/config/config'

import { IReq, IRes, INext } from '@src/routes/common/types';
import { JwtPayload } from './common/type'
import { resExample } from '@src/services/common/responseData';

import HttpStatusCodes from '@src/common/HttpStatusCodes';

import UserModel from '@src/models/User';
import { Model } from 'sequelize';
import { IUser } from '@src/libcommon/modules/user';

// 生成token
export const generateToken = function (payload: JwtPayload) {
    const token =
        jwt.sign(payload, CONFIG.SECRET, {
            expiresIn: '3h',
        });
    return token;
};

// 封装 jwt.verify 为 Promise
const verifyJwtAsync = (token: string) => {
    return new Promise((resolve, reject) => {
        jwt.verify(token, CONFIG.SECRET, (err, decoded) => {
            if (err) {
                return reject(err);  // 错误直接 reject
            }
            resolve(decoded); // 成功返回解码的内容
        });
    });
};

// 验证token
export const verifyToken = async function (req: IReq, res: IRes, next: INext) {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) {
        throw resExample({
            code: HttpStatusCodes.UNAUTHORIZED,
            message: "token不存在,请重新登录",
            success: false,
            data: null,
        })
    }
    try {
        const decoded: any = await verifyJwtAsync(token);
        console.log('decoded:', decoded)
        const user = await UserModel();
        const userRes = await user.findOne({ where: { id: decoded.id } });

        if (!userRes) {
            throw resExample({
                code: HttpStatusCodes.UNAUTHORIZED,
                message: "用户不存在,请重新登录",
                success: false,
                data: null,
            });
        }

        req.user = userRes.get();
        req.userId = userRes.get().id;
        next();
    } catch (err) {
        if (err instanceof jwt.TokenExpiredError) {
            throw resExample({
                code: HttpStatusCodes.UNAUTHORIZED,
                message: "token已过期,请重新登录",
                success: false,
                data: null,
            });
        }
        console.error('Token verification error', err);
        throw resExample({
            code: HttpStatusCodes.UNAUTHORIZED,
            message: "token无效,请重新登录",
            success: false,
            data: null,
        });
    }

};